package com.easyxu.kubernetes.filebrowser.service.executor;

import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.openapi.models.V1Deployment;
import io.kubernetes.client.openapi.models.V1Pod;
import io.kubernetes.client.openapi.models.V1PodList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class PodQryCmdExe {

    private DeploymentQryCmdExe deploymentQryCmdExe;

    @Autowired
    public PodQryCmdExe(DeploymentQryCmdExe deploymentQryCmdExe){
        this.deploymentQryCmdExe = deploymentQryCmdExe;
    }

    public List<V1Pod> execute(String namespace, String deployment) throws ApiException {

        List<V1Deployment> v1Deployments = deploymentQryCmdExe.execute(namespace, deployment);

        if(v1Deployments.size() > 0){
            V1Deployment v1Deployment = v1Deployments.get(0);

            Map<String, String> matchLabels = v1Deployment.getSpec().getSelector().getMatchLabels();

            StringBuilder labelBuild = new StringBuilder(",");

            for(String matchLabelKey : matchLabels.keySet()){
                labelBuild.append(matchLabelKey+"="+matchLabels.get(matchLabelKey));
            }

            CoreV1Api api = new CoreV1Api();

            V1PodList v1PodList = api.listNamespacedPod(namespace, null, null, null, null, labelBuild.substring(1), null, null, null, null);
            return v1PodList.getItems();
        }

        return new ArrayList<>();
    }

}
